package sf.md.create.prototype.deep2;

import java.io.*;

public class CloneTest3 {
    public static void main(String[] args) throws Exception

    {

        Teacher3 t1 = new Teacher3();

        t1.setAge(40);

        t1.setName("Teacher Li");



        Student3 s1 = new Student3();

        s1.setAge(20);

        s1.setName("Jack");

        s1.setTeacher(t1);



        Student3 s2 = (Student3)s1.deepCopy();



        System.out.println(s2.getAge());

        System.out.println(s2.getName());



        s1.getTeacher().setName("Teacher Wang");



        System.out.println(s2.getTeacher().getAge());

        System.out.println(s2.getTeacher().getName());

    }

}



//必须要实现Serializable接口

class Teacher3 implements Serializable

{

    private int age ;

    private String name;

    public int getAge()

    {

        return age;

    }

    public void setAge(int age)

    {

        this.age = age;

    }

    public String getName()

    {

        return name;

    }

    public void setName(String name)

    {

        this.name = name;

    }



}



//必须要实现Serializable接口，这个接口是个标识接口，没有定义任何方法

class Student3 implements Serializable

{

    private int age;



    private String name;



    private Teacher3 teacher;



    public int getAge()

    {

        return age;

    }



    public void setAge(int age)

    {

        this.age = age;

    }



    public String getName()

    {

        return name;

    }



    public void setName(String name)

    {

        this.name = name;

    }



    public Teacher3 getTeacher()

    {

        return teacher;

    }



    public void setTeacher(Teacher3 teacher)

    {

        this.teacher = teacher;

    }



    //用序列化的特点来进行深拷贝。无论有多少个对象引用都可以复制

    public Object deepCopy() throws Exception

    {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();



        ObjectOutputStream oos = new ObjectOutputStream(bos);



        oos.writeObject(this);



        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());



        ObjectInputStream ois = new ObjectInputStream(bis);



        return  ois.readObject();

    }

}